<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="35%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="auto">
        <el-form-item label="视频名称" prop="videoName">
          <el-input v-model="formData.videoName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="视频大小" prop="videoSize">
          <el-input disabled :value="formatVideoSize(formData.videoSize)" placeholder="请输入视频大小" />
        </el-form-item>
        <el-form-item label="视频时长（s）" prop="videoDuration">
          <el-input disabled :value="formatDuration(formData.videoDuration)" placeholder="请输入视频时长（s）" />
        </el-form-item>
        <el-form-item label="视频分辨率" prop="videoResolution">
          <el-select disabled v-model="formData.videoResolution" placeholder="请选择视频分辨率">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.VIDEO_RESOLUTION)"
                       :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as VideoInfoApi from '@/api/audit/videoinfo';
import FileUpload from '@/components/FileUpload';
import VideoRecordForm from './components/VideoRecordForm.vue'

export default {
  name: "VideoInfoForm",
  components: {
    FileUpload,
    VideoRecordForm,
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        videoName: undefined,
      },
      // 表单校验
      formRules: {
        // videoPath: [{required: true, message: '视频路径不能为空', trigger: 'blur'}],
        videoName: [{required: true, message: '视频名称不能为空', trigger: 'blur'}],
        // videoSize: [{required: true, message: '视频大小不能为空', trigger: 'blur'}],
        // videoDuration: [{required: true, message: '视频时长（s）不能为空', trigger: 'blur'}],
        // videoResolution: [{required: true, message: '视频分辨率不能为空', trigger: 'change'}],
      },
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await VideoInfoApi.getVideoInfo(id);
          this.formData = res.data;
          this.title = "修改视频信息";
        } finally {
          this.formLoading = false;
        }
      }
      this.title = "新增视频信息";
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 拼接子表的数据
        // data.videoRecord = this.$refs['videoRecordFormRef'].getData();
        // 修改的提交
        if (data.id) {
          const param = {
            id: data.id,
            videoName: data.videoName
          }
          await VideoInfoApi.updateVideoInfo(param);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await VideoInfoApi.createVideoInfo(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        videoPath: undefined,
        videoName: undefined,
        videoSize: undefined,
        videoDuration: undefined,
        videoResolution: undefined,
      };
      this.resetForm("formRef");
    },
    /** 自定义操作======================================== */
    // 转换视频大小到 MB，并保留两位小数
    formatVideoSize(sizeInBytes) {
      if (!sizeInBytes) return "0 MB";
      const sizeInMB = sizeInBytes / (1024 * 1024);
      return `${sizeInMB.toFixed(2)} MB`;
    },
    // 格式化视频时间长度 0分00秒
    formatDuration(milliseconds) {
      if (!milliseconds) return "0分00秒"; // 处理空值或无效情况
      const totalSeconds = Math.floor(milliseconds / 1000); // 将毫秒转换为秒
      const minutes = Math.floor(totalSeconds / 60);
      const remainingSeconds = Math.floor(totalSeconds % 60);
      return `${minutes}分${remainingSeconds < 10 ? "0" : ""}${remainingSeconds}秒`;
    },
  }
};
</script>
